package com.hoshiicloud.as2c.minipro.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.controller.BaseController;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.as2c.minipro.dto.ExtSpuTagsDto;
import com.hoshiicloud.as2c.minipro.feign.GoodsFeignService;
import com.hoshiicloud.as2c.minipro.param.ExtSpuQueryParam;
import com.hoshiicloud.as2c.minipro.vo.ImagesVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangcheng
 * @version 1.0
 * @title: GoodsController
 * @description: 商品相关接口Controller
 * @date 2019/5/31 15:01
 * @mail maiboyc@163.com
 */
@Slf4j
@RestController
@RequestMapping("/goods")
@Api(value = "商品管理", tags = {"商品相关操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class GoodsController extends BaseController {

    // 商品图片统一前缀（暂时使用甲方提供的地址）
    @Value("${image.url}")
    @Autowired
    private String url;

    // 商品微服务Service
    @Autowired
    private GoodsFeignService goodsFeignService;

    // 获取首页banner图片
    @GetMapping("/getBanners/{platformId}")
    @ApiOperation(value = "获取首页banner图片", notes = "获取首页banner图片", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<String>> getBanners(@PathVariable("platformId") String platformId) {
        return Response.data(null);
    }

    /**
     * 商品列表
     * @param param 查询参数
     * @return Response<IPage<ExtSkuDto>>
     */
    @PostMapping("/getGoodsList")
    @ApiOperation(value = "获取商品列表", notes = "获取商品列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<Map<String,Object>>> getSpusWithMiniPrice(@RequestBody ExtSpuQueryParam param) {
        Response<Page<Map<String,Object>>> rs;
        try {
            rs = goodsFeignService.getSpusWithMiniPrice(param);
        } catch (Exception e) {
            log.error("查询商品列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("查询商品列表异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 根据类目查询商品列表
     * @param param 查询参数
     * @return Response<Page<Map<String,Object>>>
     */
    @PostMapping("/getGoodsListByCategoryId")
    @ApiOperation(value = "根据类目查询商品列表", notes = "根据类目查询商品列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<Map<String,Object>>> getSpusByStoreIdAndCategoryId(@RequestBody ExtSpuQueryParam param) {
        Response<Page<Map<String,Object>>> rs;
        try {
            rs = goodsFeignService.getSpusByStoreIdAndCategoryId(param);
        } catch (Exception e) {
            log.error("根据类目查询商品列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据类目查询商品列表异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 获取商品详情
     * @param id ID
     * @return Response<Map<String,Object>>
     */
    @GetMapping("/getGoodsDetail/{id}")
    @ApiOperation(value = "获取商品详情", notes = "获取商品详情")
    public Response<Map<String,Object>> getGoodsDetail(@PathVariable("id") Long id) {
        Response<Map<String,Object>> rs = null;
        try {
            Response<List<Map<String,Object>>> goodsDetails = goodsFeignService.getGoodsDetail(id);
            if (null != goodsDetails && goodsDetails.getCode() == 200 && null != goodsDetails.getData()) {
                for (Map<String,Object> map: goodsDetails.getData()) {
                    map.get("spec");
                    Map<String,Object> temp = JSON.parseObject((String) map.get("spec"), Map.class);
                    if (null != temp.get("spec1")) {
                        Map<String,Object> data = new HashMap<>();
                        data.put("spuId",map.get("spuId"));
                        data.put("skuId",map.get("skuId"));
                        data.put("title",map.get("title"));
                        data.put("description",getDescImages((String)map.get("description")));
                        data.put("categories",getCategoriesOrTags((String)map.get("categories")));
                        Response<List<ExtSpuTagsDto>> rs_tags = goodsFeignService.getTagsBySpuId(Long.parseLong((String)map.get("spuId")));
                        data.put("tags",rs_tags.getData());
                        data.put("minPrice",map.get("minPrice"));
                        data.put("maxPrice",map.get("maxPrice"));
                        data.put("spec",map.get("spec"));
                        data.put("images",getImages((String)map.get("images")));
                        rs = Response.data(data);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取商品详情异常"+"["+e.getMessage()+"]");
            rs = Response.failed("获取商品详情异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 根据spuId获取标签信息
     * @param spuId 商品SPU主键
     * @return Response<List<ExtSpuTagsDto>>
     */
    @GetMapping("/getTagsBySpuId/{spuId}")
    @ApiOperation(value = "根据spuId获取标签信息", notes = "根据spuId获取标签信息")
    public Response<List<ExtSpuTagsDto>> getTagsBySpuId(@PathVariable("spuId") Long spuId) {
        Response<List<ExtSpuTagsDto>> rs;
        try {
            rs = goodsFeignService.getTagsBySpuId(spuId);
        } catch (Exception e) {
            log.error("根据spuId获取标签信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据spuId获取标签信息异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 根据标签ID获取标签信息
     * @param id ID
     * @return Response<ExtSpuTagsDto>
     */
    @GetMapping("/getTagById/{id}")
    @ApiOperation(value = "根据ID获取标签信息", notes = "根据ID获取标签信息")
    public Response<ExtSpuTagsDto> getTagById(@PathVariable("id") Long id) {
        Response<ExtSpuTagsDto> rs;
        try {
            rs = goodsFeignService.getTagById(id);
        } catch (Exception e) {
            log.error("根据ID获取标签信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据ID获取标签信息异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 转换商品描述图
     * @param description 商品描述
     * @return List<ImagesVO>
     */
    private List<ImagesVO> getDescImages(String description) {
        List<ImagesVO> list;
        if (StringUtils.isNotEmpty(description)) {
            list = new ArrayList<>();
            String[] image = description.split(",");
            if (image.length > 0) {
                for (String s: image) {
                    if (s.indexOf(".jpg") > -1 || s.indexOf(".png") > -1 || s.indexOf(".JPG") > -1) {// 图片
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(0);
                        list.add(imagesVO);
                    } else {// 视频
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(1);
                        list.add(imagesVO);
                    }
                }
            }
        } else {
            list = new ArrayList<>();
        }
        return list;
    }

    /**
     * 转换商品轮播图
     * @param images 轮播图图片ID字符串
     * @return List<ImagesVO>
     */
    private List<ImagesVO> getImages(String images) {
        List<ImagesVO> list;
        if (StringUtils.isNotEmpty(images)) {
            list = new ArrayList<>();
            String[] image = images.split(",");
            if (image.length > 0) {
                for (String s: image) {
                    if (s.indexOf(".jpg") > -1 || s.indexOf(".png") > -1 || s.indexOf(".JPG") > -1) {// 图片
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(0);
                        list.add(imagesVO);
                    } else {// 视频
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(1);
                        list.add(imagesVO);
                    }
                }
            }
        } else {
            list = new ArrayList<>();
        }
        return list;
    }

    /**
     * 转换类目或标签
     * @param categories
     * @return List<String>
     */
    private List<String> getCategoriesOrTags(String categories) {
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(categories)) {
            String[] temp = categories.split(",");
            for (String s: temp) {
                list.add(s);
            }
        }
        return list;
    }

}
